<?php
/**
 * Created by PhpStorm.
 * User: yellow
 * Date: 2019/5/15
 * Time: 11:24
 */

namespace app\admin\logic;

use app\admin\logic\code\ErrorCode;
use app\common\model\Config;
use think\Error;
use think\facade\Cache;

class ConfigLogic extends BaseLogic{

    private static $configGroup;
    private $configModel;

    public function __construct()
    {
        parent::__construct();
        self::$configGroup = ['base'=>1];
        $this->configModel = new Config();
    }

    public function configInfo(){
        $configList = $this->configModel->all();
        if ($configList){
            foreach ($configList as $key=>$val){
                $temp[$val->group_type][$val->key]['value'] = $val->value;
                $temp[$val->group_type][$val->key]['id'] = $val->id;
            }
            return ajaxArr(ErrorCode::$SUCCESS, 'success', $temp);
        } else{
            return ajaxArr(ErrorCode::$LISTNULL, '配置不存在');
        }
    }

    /**
     * 操作配置
     * @param $data
     * @return mixed
     */
    public function handle($data){
        $cacheTemp = [];
        foreach (self::$configGroup as $key=>$val){
            $configData['group_type'] = $val;
            if ($data[$key]){
                foreach ($data[$key] as $cKey=>$cVal){
                    $configData['key'] = $cKey;
                    $configData['value'] = $cVal['value'];
                    if ($cVal['id']){
                        $configData['id'] = $cVal['id'];
                    }
                    $cacheTemp[$cKey] = $cVal['value'];
                    $allData[] = $configData;
                }
            }
        }
        try{
            $res = false;
            if ($allData){
                $res = $this->configModel->saveAll($allData);
            }
            if ($res){
                //更新配置缓存
                Cache::set('config_temp', $cacheTemp);
                return ajaxArr(ErrorCode::$SUCCESS, '操作成功');
            } else{
                return ajaxArr(ErrorCode::$OPERATIONERROR, '操作失败');
            }
        } catch (\Exception $e){
            return ajaxArr(ErrorCode::$OPERATIONERROR, '操作失败');
        }
    }

}